<template>
  <!-- 明日预约 -->
  <workStatistics :todayData="today"></workStatistics>
  <zsearch  v-loading="loading">
      <template #title>
        <span>明日预约</span>
      </template>
      <template #date>
        <el-date-picker
            class="date-1"
            type="date"
            v-model="date"
            placeholder="选择日期"
            @change="handleChangeDate"
            >
        </el-date-picker>
      </template>
      <template #select>
        <el-input class="input-1" v-model="name" placeholder="患者/电话/病历号"></el-input>
        <el-select class="select-1" v-model="doctorId" clearable filterable placeholder="选择医生">
          <el-option
            v-for="item in optionsDoctor"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
	      <el-button class="btn-2">导出</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='columns'
          :height="'100%'"
          :isshowOperation="true"
          @onToDetail="onToDetail"
          :width="'240'"
        >
        <template #default="slotScope">
          <el-button type="text" class="operation" @click="handleEditItem(slotScope.rowData)" >修改预约</el-button>
          <el-button type="text" class="operation" @click="handleCancelItem(slotScope.rowData)">取消预约</el-button>
        </template>
        </ztable>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total"
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>


     <!-- 取消预约 -->
  <zdialog title="取消预约" @handleClose="closeDialog" v-model="dialogCancelVisible" :btnData="dialogCancelBtn">
      <template #body>
        <div class="person-info">
          <span>患者: <span class="name">{{ personName}}</span></span>
          <span>预约时间: {{subscribeTime}}</span>
        </div>
			</template>
  </zdialog>

   <!-- 新增/挂号/ 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
			<zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
			
			<zregister v-if="isADD === 'register'"
				@cancel="cancel" 
				@handlebtn="handlebtn"
				></zregister>

			<zmakeanapp v-if="isADD === 'makeanapp'"
				@handlebtn="handlebtn"
				@cancel="cancel"
        @reloadList="reloadList"
        :makeanappInfo="makeanappInfo"

				></zmakeanapp>
	</el-drawer>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"
import { debounce } from "../../utils/debounce"

import useConfgin from '../../hook/getconfig'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"
import workStatistics from "../../components/workStatistics/work.vue"

import { Option } from "../../types"
import { getOldDate, getNowDate } from '../../utils/nowDate'
import { getweekDate } from "../../usefn/getBirthday"
import { getDoctors } from "../../usefn/getDoctor"
import useSetAddLog from "../../hook/setAddLog"
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'


const configID = 529
export default defineComponent({
  name: 'AppointmentTomorrow',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog,

    zmakeanapp,
    zaddpatient,
    zregister,

    workStatistics
  },
  setup() {
    let search = reactive({
      date: getOldDate(),
      name:'',
      current: 1,
      size: 10,
      total: 0,

      doctorId: null,
      optionsDoctor: [] as Option[],

      loading: false
    })
    let today = reactive({
      todayNewCustomer: 0,
      todayNewSub: 0,
      todayNewCollection: 0,
      todayNewAccessLog: 0,
      todayNewSickMedicalRecords: 0
    })
    const router = useRouter()
    const request = useRequet({ path: "" });
    const data = ref([])
    const rowsList = useConfgin(configID)
    const columns = rowsList.groupDataList.value;

    const btnData = [
      {
        name: '确定预约',
        btn: 'sick:subScribe:complete'
      },
    ] as any[]
    const setConfirmAppoint = (id: number) => {
      request.sendRequest({
        address: `customer/subscribe/userCanComing/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('确定预约' + resp.msg)
          ElMessage.success('确定预约' + resp.msg)
          req()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('确定预约' + resp.msg)
          
        },
        method: "POST",
      })
    }

    const handleChangeDate = (e: Date) => {
      search.date = getNowDate(e)
    }

    const getdoctor = async() => {
      search.optionsDoctor = await getDoctors()
    }
    getdoctor()

    const req = () => {
      search.loading = true
      request.sendRequest({
        address: '/customer/subscribe/getSubScribePageBySubCompanyId',
        params: {
          day: search.date,
          customerQueryValue: search.name,
          doctorId: search.doctorId,
          size: search.size,
          current: search.current
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
					data.value = resp.data.records
          search.total = resp.data.total
          search.current = resp.data.current

          data.value.forEach((i:any, index) => {
            console.log(i)
            i.subscribeTime = getweekDate(i.subscribeTime)
            i.index = ++index
          })

          let result:any = window.localStorage.getItem('jurisdiction')
          let list = JSON.parse(result)
          let btncode = btnData[0].btn
          if(list.includes(btncode)) {
            data.value.forEach((item: any) => {
              console.log(item)
              let obj = JSON.parse(JSON.stringify(btnData))
              if(item.status === '完成') {
                obj[0].disable = true
              } else {
                obj[0].disable = false
              }
              obj[0].func = (data:any, index: number) => {
                  
                  let {id, customerName} = data
                  ElMessageBox.confirm(`确定患者【${customerName}】预约`, '确定预约', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }).then(() => {
                    setConfirmAppoint(id)
                    data.btnData[index].disable = true
                  }).catch(() => {
                      ElMessage({
                        type: 'info',
                        message: '已取消',
                      });
                  })
                  
                },
              
              item.btnData = obj
            })
          }


          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }
    req()

    // 去详情
    const onToDetail = (id: number) => {
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
    }

    const getTodayStatistics = () => {
      request.sendRequest({
        address: '/pay/order/todayStatistics',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
	
          console.log(resp.data)
          today.todayNewCustomer = resp.data.todayNewCustomer
          today.todayNewSub = resp.data.todayNewSub
          today.todayNewCollection = resp.data.todayNewCollection
          today.todayNewAccessLog = resp.data.todayNewAccessLog
          today.todayNewSickMedicalRecords = resp.data.todayNewSickMedicalRecords

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }
    getTodayStatistics()

    const debounceRefresh = debounce(req, 1000)
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}

    // 修改预约
    const handleEditItem = async(rowData: any) => {
      console.log('修改预约', rowData)
      let {id} = rowData
      await getMakeanapp(id)

      showDrawer.value = true
      title.value = "修改预约"
      isADD.value = 'makeanapp'
    }
    const personName = ref('')
    // 预约id
    const personID = ref('')
    const subscribeTime = ref('')
    // 取消预约
    const handleCancelItem = (rowData: any) => {
      console.log(rowData)
      personID.value = rowData.id
      personName.value = rowData.customerName
      subscribeTime.value = rowData.subscribeTime
      dialogCancelVisible.value = true
    }
    // 关闭弹框
    const closeDialog = () => {
      dialogCancelVisible.value = false
    }
    const dialogCancelVisible = ref(false)
    const dialogCancelBtn = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogCancelVisible.value = false
				}
      },
      {
        name: '确定',
				func: (data:object) => {
					console.debug('确定',JSON.parse(JSON.stringify(data)))
          request.sendRequest({
            address: 'customer/subscribe/cancelLog',
            params: {
              id: personID.value
            },
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error('取消预约' + resp.msg)
              ElMessage.success('取消预约' + resp.msg)
              closeDialog()
              req()
            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg)
              
            },
            method: "POST",
          })
				}
      },
    ]

    // 刷新列表
    const reloadList = () => {
      req()
    }

    const makeanappInfo = ref({} as any)
    // 获取预约信息
    const getMakeanapp = (id: number) => {
      return new Promise((resolve, reject) => {
          request.sendRequest({
          address: `customer/subscribe/getSubscribeById/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            makeanappInfo.value = resp.data
            resolve('')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            reject()
          },
          method: "GET",
        })
      })
    }

    // 抽屉 --》 新建预约部分
    const showDrawer = ref(false)
    const title = ref('')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }
    return {
      data,
      columns,
      ...toRefs(search),
      today,
      btnData,
      onToDetail,

      handleCurrentChange,
      handleSizeChange,
      hanledSearch,
      handleChangeDate,

      handleEditItem,
      handleCancelItem,
      closeDialog,
      dialogCancelVisible,
      dialogCancelBtn,
      personName,
      personID,
      subscribeTime,

      reloadList,
      makeanappInfo,
      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,
    }
  }
})
</script>

<style lang="scss" scoped>
.select-1 {
  padding-left: 8px;
}

.person-info {
  padding: 10px 0;

  & > span {
    padding-right: 15px;

    .name {
      background: #4094ff;
      color: white;
      padding: 3px 5px;
      border-radius: 4px;
    }
  }
}
</style>